/*
 * @Author: your name
 * @Date: 2022-04-29 13:44:12
 * @LastEditTime: 2022-04-29 15:57:12
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /umi-demo/src/pages/demo/VirtualList/index.js
 */
import { useState, useRef, useEffect } from 'react';
import './index.less';
const bigData = new Array(50).fill(1).map((item, index) => index);

export default (props) => {
    const containerHeight = useRef();
    const itemHeight = useRef(50);

    const startIndex = useRef(0);
    const endIndex = useRef();
    const startOffset = useRef(0);
    const [listData, setListData] = useState([]);

    useEffect(() => {
        containerHeight.current = document.querySelector('.virtual-list-container')?.getBoundingClientRect().height;
        endIndex.current = Math.ceil(containerHeight.current / itemHeight.current) || 0;
        handleScroll();
    }, []);

    function getInfo() {
        // 可视区域显示的个数
        const visibleCount = Math.ceil(containerHeight.current / itemHeight.current);

        const scrollTop = document.querySelector('.virtual-list-container').scrollTop;

        // 启示位置
        startIndex.current = Math.floor(scrollTop / itemHeight.current);
        // 结束位置
        endIndex.current = Math.floor(startIndex.current + visibleCount);
        // 计算startOffset
        startOffset.current = scrollTop - (scrollTop % itemHeight.current);
        // 截取可视区域的数据
        const visibleData = bigData.slice(startIndex.current, endIndex.current);

        setListData(visibleData);
        console.log('~~', startIndex.current, endIndex.current, visibleData);
    }

    function handleScroll() {
        getInfo();
    }

    function getTransform() {
        return `translate3d(0, ${startOffset.current}px, 0)`;
    }
    return (
        <div>
            <div className="virtual-list-container" onScroll={handleScroll}>
                <div id="occupy" style={{ height: bigData.length * 50 + 'px' }}></div>
                <div id="items" style={{ transform: getTransform() }}>
                    {listData.map((key) => (
                        <div key={key} className="list-item">
                            {key}
                        </div>
                    ))}
                </div>
            </div>
            <a href="https://juejin.cn/post/6844903982742110216" target="_blank">
                文章参考
            </a>
        </div>
    );
};
